package com.stone.framework.core.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.stone.framework.core.context.UUIDContext;
import com.stone.framework.message.ResMessage;

@ControllerAdvice
public class ResMessageAdvice implements ResponseBodyAdvice<ResMessage<Object>> {

    @Value("${stone.log.res.enabled:true}")
    private boolean enabled = true;

    private static final Logger LOGGER = LoggerFactory.getLogger(ResMessageAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (ResMessage.class.isAssignableFrom(returnType.getMethod().getReturnType())) {
            return true;
        }
        return false;
    }

    @Override
    public ResMessage<Object> beforeBodyWrite(ResMessage<Object> body, MethodParameter returnType,
        MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
        ServerHttpRequest request, ServerHttpResponse response) {
        this.buildUUID(body);

        if (enabled) {
            LOGGER.info("response body: {}", body);
        }
        return body;
    }

    @SuppressWarnings("deprecation")
    private void buildUUID(ResMessage<Object> body) {
        try {
            String uid = UUIDContext.build().get().orElse("");
            body.setUid(uid);
        } finally {
            UUIDContext.build().remove();
        }
    }

}
